<template>
  <!-- 用户管理模块的头部格式 -->
  <div v-if="currentView === 'userManagement'" class="management-section">
          <el-card>
            <div class="table-header">
              <el-button type="primary" @click="showAddDialog = true">
                <el-icon><Plus /></el-icon>添加用户
              </el-button>
              <div class="search-container">
                <el-form :inline="true" :model="searchForm" class="advanced-search">
                  <el-form-item label="用户名">
                    <el-input v-model="searchForm.userName" placeholder="用户名" clearable />
                  </el-form-item>
                  <el-form-item label="真实姓名">
                    <el-input v-model="searchForm.userTrueName" placeholder="真实姓名" clearable />
                  </el-form-item>
                  <el-form-item label="手机号">
                    <el-input v-model="searchForm.userPhoneNumber" placeholder="手机号" clearable />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="searchUsers">搜索</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                  </el-form-item>
                </el-form>
                
              </div>
            </div>

            <el-table :data="users" border style="width: 100%">
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="userName" label="用户名" width="120" />
              <el-table-column label="头像" width="100">
                <template #default="{row}">
                  <el-avatar :src="row.userPhoto" :size="50">
                    <template #default>
                      <UserFilled v-if="!row.userPhoto" />
                    </template>
                  </el-avatar>
                </template>
              </el-table-column>
              <el-table-column prop="password" label="密码(MD5)" width="180">
                <template #default="scope">
                  <el-tooltip effect="dark" :content="scope.row.password" placement="top">
                    <span>{{ scope.row.password.substring(0, 6) }}...</span>
                  </el-tooltip>
                </template>
              </el-table-column>
              <el-table-column prop="userTrueName" label="真实姓名" width="120" />
              <el-table-column prop="userPhoneNumber" label="手机号" width="150" />
              <el-table-column prop="userEmail" label="邮箱" width="180" />
              <el-table-column prop="createTime" label="创建时间" width="180" />
              <el-table-column label="操作" width="180">
                <template #default="scope">
                  <el-button size="small" @click="handleEdit(scope.row)"
                    >编辑</el-button
                  >
                  <el-button
                    size="small"
                    type="danger"
                    @click="handleDelete(scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>

            <el-pagination
              v-model:current-page="currentPage"
              :page-size="pageSize"
              :total="totalUsers"
              layout="prev, pager, next"
              @current-change="fetchUsers"
            />
          </el-card>

          <!-- 添加用户的对话框 -->
          <el-dialog v-model="showAddDialog" title="添加用户" width="30%">
            <el-form :model="newUser" label-width="80px">
              <el-form-item label="用户名" required>
                <el-input v-model="newUser.userName" placeholder="请输入用户姓名" />
              </el-form-item>
              <el-form-item label="用户密码" required>
                <el-input v-model="newUser.password" type="password" placeholder="请输入密码" show-password />
              </el-form-item>
              <el-form-item label="用户角色" required>
                <el-select v-model="newUser.role" placeholder="请选择角色">
                  <el-option label="用户" value="用户" />
                  <el-option label="管理员" value="管理员" />
                  <el-option label="商家" value="商家" />
                </el-select>
              </el-form-item>
            </el-form>
            <template #footer>
              <el-button @click="showAddDialog = false">取消</el-button>
              <el-button type="primary" @click="addUser">确认</el-button>
            </template>
          </el-dialog>

          <!-- 编辑用户密码对话框 -->
          <el-dialog v-model="showEditDialog" title="修改用户密码" width="30%">
            <el-form :model="currentEditUser" label-width="80px">
              <el-form-item label="用户名">
                <el-input v-model="currentEditUser.userName" disabled />
              </el-form-item>
              <el-form-item label="新密码" required>
                <el-input v-model="currentEditUser.password" type="password" placeholder="请输入新密码" show-password />
              </el-form-item>
            </el-form>
            <template #footer>
              <el-button @click="showEditDialog = false">取消</el-button>
              <el-button type="primary" @click="updateUser">确认</el-button>
            </template>
          </el-dialog>
        </div>

        
      
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { store } from '@/common/store'
import router from '@/router'
import {
  User,
  Document,
  Goods,
  DataAnalysis,
  Calendar,
  Plus,
  Lock,
  UserFilled//图标导入
} from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

// 当前视图
const currentView = ref('userManagement')

// 模块标题映射
const moduleTitles = {
  userManagement: '用户管理',
  newsManagement: '资讯管理',
  productView: '商品界面',
  productData: '商品数据管理',
  appointment: '预约管理',
  auth: '权限管理',
  userInfo: '个人信息修改'
}

// 用户管理相关数据
const users = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const totalUsers = ref(0)
const searchQuery = ref('')
const searchForm = ref({
  userName: '',
  userTrueName: '',
  userPhoneNumber: ''
})
const showAddDialog = ref(false)
const newUser = ref({
  userName: '',
  password: '',
  role: ''
})
const showEditDialog = ref(false)
const currentEditUser = ref({
  userName: '',
  password: ''
})

// 删除用户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除用户 ${row.userName} 吗?`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    //token获取
    const token = localStorage.getItem('adminToken') || ''
    const res = await axios.delete('/tUserInfo/deleteUserInfo', {
      params: {
        userName: row.userName
      },
      headers: {
        Authorization: `Bearer ${token}`
      }
    })
    
    if (res.data.code === 200) {
      ElMessage.success('删除用户成功')
      fetchUsers() // 刷新用户列表
    } else {
      ElMessage.error(res.data.message || '删除用户失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      if (error.response?.status === 401) {
        ElMessage.error('登录已过期，请重新登录')
        router.push('/login')
      } else {
        ElMessage.error('删除用户失败: ' + error)
      }
    }
  }
}

const handleEdit = (row) => {
  currentEditUser.value = {
    id: row.id,
    userName: row.userName,
    password: ''
  }
  showEditDialog.value = true
}
//点击编辑按钮后更新用户密码
const updateUser = async () => {
  try {
    if (!currentEditUser.value.password) {
      ElMessage.warning('请输入新密码')
      return
    }

    const token = localStorage.getItem('adminToken') || ''
    const res = await axios.put('/tUserInfo/modifyUserInfo', {
      id: currentEditUser.value.id,
      userName: currentEditUser.value.userName,
      password: currentEditUser.value.password
    }, {
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    })

    if (res.data.code === 200) {
      ElMessage.success('修改密码成功')
      showEditDialog.value = false
      fetchUsers() // 刷新用户列表
    } else {
      ElMessage.error(res.data.message || '修改密码失败')
    }
  } catch (error) {
    if (error.response?.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
      router.push('/login')
    } else {
      ElMessage.error('修改密码失败: ' + error.message)
    }
  }
}

const addUser = async () => {
  try {
    if (!newUser.value.userName || !newUser.value.password || !newUser.value.role) {
      ElMessage.warning('请填写完整信息')
      return
    }

    const token = localStorage.getItem('adminToken') || ''
    const res = await axios.post('/tUsers/register', {
      userName: newUser.value.userName,
      password: newUser.value.password,
      角色: newUser.value.role
    }, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    })

    if (res.data.code === 200) {
      ElMessage.success('添加用户成功')
      showAddDialog.value = false
      newUser.value = { userName: '', password: '', role: '' }
      fetchUsers() // 刷新用户列表
    } else {
      ElMessage.error(res.data.message || '添加用户失败')
    }
  } catch (error) {
    if (error.response?.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
      router.push('/login')
    } else {
      ElMessage.error('添加用户失败: ' + error.message)
    }
  }
}





// 获取用户列表
// 高级搜索用户
const searchUsers = async () => {
  try {
    const token = localStorage.getItem('adminToken') || ''
    const params = {}
    if (searchForm.value.userName) params.userName = searchForm.value.userName
    if (searchForm.value.userTrueName) params.userTrueName = searchForm.value.userTrueName
    if (searchForm.value.userPhoneNumber) params.userPhoneNumber = searchForm.value.userPhoneNumber

    const res = await axios.get('/tUserInfo/selectById', {
      params,
      headers: {
        Authorization: `Bearer ${token}`
      }
    })
    if (res.data.code === 200) {
      users.value = res.data.data.map(user => ({
        id: user.id,
        userName: user.userName,
        password: user.password,
        userTrueName: user.userTrueName,
        userPhoneNumber: user.userPhoneNumber,
        userEmail: user.userEmail,
        userPhoto: user.userPhoto,
        createTime: user.createTime
      }))
      totalUsers.value = res.data.data.length
      ElMessage.success('搜索成功')
    } else if (res.data.code === 401) {
      ElMessage.error('登录已过期，请重新登录')
      router.push('/login')
    } else {
      ElMessage.error(res.data.message || '搜索失败')
    }
  } catch (error) {
      if (error.response?.status === 401) {
        ElMessage.error('登录已过期，请重新登录')
        router.push('/login')
      } else {
        ElMessage.error('搜索失败: ' + error)
      }
  }
}

// 重置搜索表单
const resetSearch = () => {
  searchForm.value = {
    userName: '',
    userTrueName: '',
    userPhoneNumber: ''
  }
  fetchUsers()
}

const fetchUsers = async () => {
  try {
    const token = localStorage.getItem('adminToken') || ''
    const res = await axios.get('/tUserInfo/getAllUserInfo', {
      params: {
        currentPage: currentPage.value,
        size: pageSize.value,
      },
      headers: {
        Authorization: `Bearer ${token}`
      }
    })
    if (res.data.code === 200) {
      // 根据API响应格式设置用户数据和总数
      users.value = res.data.data.map(user => ({
        id: user.id,
        userName: user.userName,
        password: user.password, // 添加密码字段
        userTrueName: user.userTrueName,
        userPhoneNumber: user.userPhoneNumber,
        userEmail: user.userEmail,
        userIdNumber: user.userIdNumber,
        userPhoto: user.userPhoto,
        createTime: user.createTime
      }))
      // 假设API返回所有数据，前端分页
      totalUsers.value = res.data.data.length
    } else if (res.data.code === 401) {
      ElMessage.error('登录已过期，请重新登录')
      router.push('/login')
    } else {
      ElMessage.error(res.data.message || '获取用户列表失败')
    }
  } catch (error) {
      if (error.response?.status === 401) {
        ElMessage.error('登录已过期，请重新登录')
        router.push('/login')
      } else {
        ElMessage.error('获取用户列表失败: ' + error)
      }
  }
}



// 初始化获取数据
onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>


.table-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.module-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 80vh;
}

.module-placeholder h2 {
  color: #1e88e5;
  margin-bottom: 20px;
}
</style>
